{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "e6453885",
   "metadata": {},
   "source": [
    "### Test intergenic read count and coverage calculation for duplications "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bf5b0b23",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "from pathlib import Path\n",
    "import pysam\n",
    "from pybedtools import BedTool\n",
    "from io import StringIO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2fb33e04",
   "metadata": {},
   "outputs": [],
   "source": [
    "wkdir = \"/lustre/scratch126/humgen/projects/interval_rna/interval_rna_seq/thomasVDS/misexpression_v3/\"\n",
    "wkdir_path = Path(wkdir)\n",
    "# inputs \n",
    "vrnt_id = \"408686\"\n",
    "tx_read_info_path=wkdir_path.joinpath(\"6_misexp_dissect/tx_readthrough/duplications/misexp_dup_tx_readthrough_candidates.tsv\")\n",
    "misexp_cntrl_bams_dir=wkdir_path.joinpath(\"6_misexp_dissect/bams\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "658c3e1b",
   "metadata": {},
   "outputs": [],
   "source": [
    "misexp_cntrl_bams_path = Path(misexp_cntrl_bams_dir)\n",
    "misexp_tx_read_vrnt_feat_df = pd.read_csv(tx_read_info_path, sep=\"\\t\", dtype={\"vrnt_id\": str})\n",
    "\n",
    "intergenic_cov_df_list = []\n",
    "\n",
    "# get SV information\n",
    "misexp_vrnt_id_df = misexp_tx_read_vrnt_feat_df[misexp_tx_read_vrnt_feat_df.vrnt_id == vrnt_id]\n",
    "sv_start = misexp_vrnt_id_df.sv_start.unique()[0]\n",
    "sv_end = misexp_vrnt_id_df.sv_end.unique()[0]\n",
    "chrom = misexp_vrnt_id_df.chrom.unique()[0]\n",
    "seq_name = chrom.split(\"chr\")[1]\n",
    "# misexpressed genes \n",
    "misexp_genes = misexp_vrnt_id_df[misexp_vrnt_id_df.vrnt_id == vrnt_id].gene_id.unique()\n",
    "for gene_id in misexp_genes:\n",
    "    # get gene information\n",
    "    misexp_vrnt_id_gene_df = misexp_vrnt_id_df[misexp_vrnt_id_df.gene_id == gene_id]\n",
    "    gene_strand = misexp_vrnt_id_gene_df.gene_strand.unique()[0]\n",
    "    gene_start = misexp_vrnt_id_gene_df.gene_start.unique()[0]\n",
    "    gene_end = misexp_vrnt_id_gene_df.gene_end.unique()[0]\n",
    "    # intergenic region \n",
    "    if gene_strand == '+': \n",
    "        start = sv_start\n",
    "        end = gene_start\n",
    "    elif gene_strand == \"-\":\n",
    "        start = gene_end\n",
    "        end = sv_end\n",
    "    else:\n",
    "        raise ValueError(f\"{gene_strand} not recognised.\") \n",
    "    # intergenic region bed\n",
    "    vrnt_gene_id = f\"{vrnt_id}_{gene_id}\"\n",
    "    intergenic_reg = BedTool(f'{chrom} {start} {end} {vrnt_gene_id} 0 {gene_strand}', from_string=True)\n",
    "    # variant bams \n",
    "    vrnt_bams_dir = misexp_cntrl_bams_path.joinpath(f\"{vrnt_id}\")\n",
    "    vrnt_bams_path_list = vrnt_bams_dir.glob(\"*.bam\")\n",
    "    # compute coverage metrics over intergenic regions\n",
    "    for path in vrnt_bams_path_list:  \n",
    "        bam_bed = BedTool(path)\n",
    "        # compute coverage metrics only on strand with misexpressed gene \n",
    "        intergenic_cov_str = StringIO(str(intergenic_reg.coverage(bam_bed, split=True, s=True)))\n",
    "        intergenic_cov_df = pd.read_csv(intergenic_cov_str, sep=\"\\t\", header=None)\n",
    "        if intergenic_cov_df.shape[0] != 1: \n",
    "            raise ValueError(\"Empty intergenic region\")\n",
    "        intergenic_cov_df[\"vrnt_id\"] = vrnt_id\n",
    "        intergenic_cov_df[\"gene_id\"] = gene_id\n",
    "        rna_id = path.name.split(\".\")[0]\n",
    "        intergenic_cov_df[\"rna_id\"] = rna_id\n",
    "        intergenic_cov_df_list.append(intergenic_cov_df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "d9ad3a1e",
   "metadata": {},
   "outputs": [],
   "source": [
    "intergenic_reads_columns = {0: \"chrom\", 1:\"sv_start\", 2:\"sv_end\", 3:\"vrnt_gene_id\", \n",
    "                            4:\"score\", 5:\"misexp_gene_strand\",6:\"features\", 7:\"coverage\", \n",
    "                            8:\"total_len\", 9: \"cov_fraction\"}\n",
    "tx_read_vrnts_intergenic_cov_df = pd.concat(intergenic_cov_df_list)\n",
    "tx_read_vrnts_intergenic_cov_df = tx_read_vrnts_intergenic_cov_df.rename(columns=intergenic_reads_columns)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8ff6577c",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
